const express = require('express');
const cors = require('cors');
const path = require('path');
const { serverConfig } = require('./config/config');
const pool = require('./config/db');

const app = express();

// 中间件
app.use(cors(serverConfig.cors));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static(path.join(__dirname, '..')));

// 路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api', require('./routes/post'));
app.use('/api/user', require('./routes/user'));

// 更新用户游戏UID
app.post('/api/user/update-game-uid', async (req, res) => {
    const { userId, gameUid } = req.body;
    
    try {
        // 检查游戏UID是否已被其他用户绑定
        const [existingUsers] = await pool.query(
            'SELECT * FROM t_user WHERE game_uid = ? AND user_id != ?',
            [gameUid, userId]
        );
        
        if (existingUsers.length > 0) {
            return res.json({
                success: false,
                message: '该游戏账号已被其他用户绑定'
            });
        }
        
        // 更新用户游戏UID
        await pool.query(
            'UPDATE t_user SET game_uid = ? WHERE user_id = ?',
            [gameUid, userId]
        );
        
        res.json({
            success: true,
            message: '游戏账号绑定成功'
        });
    } catch (error) {
        console.error('更新游戏UID失败:', error);
        res.json({
            success: false,
            message: '更新游戏账号失败，请稍后重试'
        });
    }
});

// 获取用户信息
app.get('/api/user/get-profile/:userId', async (req, res) => {
    const { userId } = req.params;
    
    try {
        const [users] = await pool.query(
            'SELECT user_id, nickname, avatar, game_uid FROM t_user WHERE user_id = ?',
            [userId]
        );
        
        if (users.length === 0) {
            return res.json({
                success: false,
                message: '用户不存在'
            });
        }
        
        res.json({
            success: true,
            data: users[0]
        });
    } catch (error) {
        console.error('获取用户信息失败:', error);
        res.json({
            success: false,
            message: '获取用户信息失败'
        });
    }
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ 
        success: false,
        message: '服务器内部错误' 
    });
});

// 启动服务器
const PORT = serverConfig.port || 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});